package com.officegame;

import java.util.List;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.officeame.adapters.TablesAdapter;
import com.officegame.entities.GameTable;
import com.officegame.pulltorefresh.PullToRefreshBase;
import com.officegame.pulltorefresh.PullToRefreshListView;

public class TablesActivity extends Activity {

	private TablesAdapter tablesAdapter;
	private PullToRefreshListView list;
	private OfficeGameApplication app;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_activity_tables);
		
		app = (OfficeGameApplication) getApplication();
		
		mapUI();
		setUI();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	private void mapUI() {
		list = (PullToRefreshListView) findViewById(R.id.lv_tables);
	}
	
	private void setUI() {
		if (tablesAdapter == null) {
			setAdapter();
		}
		list.getRefreshableView().setAdapter(tablesAdapter);
		list.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener() {
			@Override
			public void onRefresh() {
				new RefreshTablesAsync().execute();
			}
		});
	}
	
	private void setAdapter() {
		tablesAdapter = new TablesAdapter(this);
	}
	
	private class RefreshTablesAsync extends AsyncTask {
		private List<GameTable> tables;

		@Override
		protected Object doInBackground(Object... params) {
			tables = app.getRestClient().getGameTables();
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			tablesAdapter.refresh(tables);
			list.onRefreshComplete();
		}
	}
	
}
